package com.simple.trade.catchs;

import com.google.common.base.Throwables;
import com.simple.common.entity.ResData;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;
import java.util.Optional;

/**
 * @author yasud
 * @date 2020年09月03日 14:10
 * @description
 */
@RestControllerAdvice
public class MyExceptionAfter {


    @ExceptionHandler
    public ResData handle(Exception ex) {
        ex.printStackTrace();
        Throwable rootCause = Throwables.getRootCause(ex);
        if (Objects.nonNull(rootCause)) {
            if (ex instanceof MethodArgumentNotValidException) {
                MethodArgumentNotValidException validException = (MethodArgumentNotValidException) ex;
                BindingResult bindingResult = validException.getBindingResult();
                Optional<ObjectError> first = bindingResult.getAllErrors().stream().findFirst();
                return first.map(v -> ResData.error(v.getDefaultMessage())).orElse(ResData.error("未知错误"));
            }
        }
        return ResData.error(ex.getMessage());
    }
}
